<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-row>
        <el-form-item  prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item  prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入用户手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item  prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item  prop="vin">
        <el-input
          v-model="queryParams.vin"
          placeholder="请输入车架号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
            <el-date-picker
              v-model="dateRange"
              size="small"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态" clearable>
          <el-option
            v-for="dict in dict.type.pay_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
        <!-- </el-row>
        <el-row> -->
            <!-- <el-form-item  prop="electricStatus">
        <el-select v-model="queryParams.electricStatus" placeholder="请选择换电状态" clearable>
          <el-option
            v-for="dict in dict.type.electric_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
          <el-form-item>
            <el-cascader
              v-model="value"
              placeholder="请选择站点"
              :show-all-levels="false"
              ref="sysCascader"
              :props="prop"
              size="small"
              @change="selectElectric($event)"
              clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <!--  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
      </el-form-item>
        </el-row>
      
    </el-form>

    <el-row :gutter="10" class="mb8" >
       <el-button icon="el-icon-connection" size="mini"  @click="summaryShow" v-if="!isShow">统计汇总展示</el-button>
        <el-button icon="el-icon-connection" size="mini"  @click="summaryShow" v-if="isShow">统计汇总关闭</el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" border ref="table_show" :show-summary="true" :summary-method="getSummaries">
      <el-table-column label="订单号" align="center" prop="orderId" width="250">
        <template slot-scope="scope" class="pre-text">
          <span style="color:#20B2AA;cursor: pointer;"
                @click="queryDetails(scope.row)">{{scope.row.orderId}}</span>
                <!-- <span style="color:#20B2AA;cursor: pointer;">{{scope.row.orderId}}</span> -->
        </template>

      </el-table-column>
      <el-table-column label="用户手机号" align="center">
      <template slot-scope="scope">  
        <span>{{ scope.row.userPhone.substr(0, 3) + '****' + scope.row.userPhone.substr(-4) }}</span>  
      </template>  
    </el-table-column>  
      <!-- <el-table-column label="车牌号" align="center" prop="licensePlate" /> -->
      <el-table-column label="订单总金额" align="center" prop="totalOrderAmount" />
      <!-- <el-table-column label="卡券抵扣金额" align="center" prop="amountCreditCard" /> -->
      <!-- <el-table-column label="余额抵扣金额" align="center" prop="payAmount" /> -->
      <el-table-column label="换电状态" align="center" prop="electricStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.electric_order_status" :value="scope.row.electricStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="支付类型" align="center" prop="payType" />
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_status" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="估算满电续航" align="center" prop="endurance" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="200"/>
      <el-table-column label="所属站点" align="center" prop="stationName" />
    </el-table>

    <el-table :data="summaryData" v-loading="loading" border v-show="isShow">
      <el-table-column label="订单金额总计(元)" prop="allOrderPrice"></el-table-column>
      <el-table-column label="卡券扣费金额总计(元)" prop="allVipPrice"></el-table-column>
      <el-table-column label="余额扣费金额总计(元)" prop="allBalance"></el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
      :visible.sync="open2"
      title="订单详情"
      size="60%"
      class="drawer-normal"
      :before-close="handleClose">
      <div class="content" style="padding:0 20px">
        <el-descriptions class="margin-top" title="用户信息" :column="3" :size="size" border>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-user"></i>
              用户名:
            </template>
            {{ form.userName }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-icon iconfont"></i>
              车牌号:
            </template>
            {{ form.licensePlate }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-tickets"></i>
              车架号:
            </template>
            {{ form.vin }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              随车公里:
            </template>
            0
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianchi iconfont"></i>
              折扣运营:
            </template>
            无折扣
            <!-- <span v-if="form.discount === 1">{{ '无折扣' }}</span>
            <span v-if="form.discount === 0">{{ '折扣有误' }}</span>
            <span v-if="form.discount && form.discount !== 1 && form.discount !== 0">{{ form.discount*10 + '折' }}</span> -->
          </el-descriptions-item>
        </el-descriptions>
        <div class="c1" style="height:30px"></div>
        <el-descriptions class="margin-top" title="订单信息" :column="2" :size="size" border>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-zhandiantuopu iconfont"></i>
              站点:
            </template>
            {{form.stationName }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              换电状态:
            </template>
            <span>
          <dict-tag :options="dict.type.electric_order_status" :value="form.electricStatus"/>
        </span>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianliang iconfont"></i>
              当前SOC:
            </template>
            {{form.oldSoc }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianliang iconfont"></i>
              新换电池SOC:
            </template>
            {{form.newSoc }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianliang iconfont"></i>
              上次更换电池SOC:
            </template>
            100
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianchi iconfont"></i>
              原电池编号:
            </template>
            {{form.oldBatteryCode}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianchi iconfont"></i>
              换电池编号:
            </template>
            {{form.newBatteryCode}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-time"></i>
              创建时间:
            </template>
            {{ parseTime(form.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-time"></i>
              换电完成:
            </template>
            {{ parseTime(form.overTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              订单号:
            </template>
            {{ form.orderId }}
            <el-tag size="small" class="electricOrder_copyOrder copyOrder" style="cursor: pointer;">复制</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" v-if="form.orderStatus === 2">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              取消原因:
            </template>
            {{ form.cancelReason }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" v-if="form.orderStatus === 2">
            <template slot="label">
              <i class="el-icon-time"></i>
              取消时间:
            </template>
            {{ form.cancelTime }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" v-if="form.orderStatus === 2">
            <template slot="label">
              <i class="el-icon-user"></i>
              取消人:
            </template>
            {{ form.cancelBy }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="c1" style="height:30px"></div>
        <el-descriptions class="margin-top" title="费用信息" :column="3" :size="size" border>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              计费模式:
            </template>
            <span >里程计费</span>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              上次换电行驶里程:
            </template>
            {{form.lastMileage}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              当前累计行驶里程:
            </template>
            {{form.nowMileage}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              减免里程:
            </template>
            {{form.derateMileage}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              计费里程:
            </template>
            {{form.chargingMileage}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              里程计费单价:
            </template>
            {{ getMileageRate(form.stationId) }}  
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              里程费用:
            </template>
            {{form.totalOrderAmount}}
          </el-descriptions-item>
		  <el-descriptions-item label-class-name="my-label">
		    <template slot="label">
		      <i class="el-icon-office-building"></i>
		      跟车里程抵扣:
		    </template>
        {{ form.useCarMiles == null ? 0 : form.useCarMiles}}
		  </el-descriptions-item>
		  <el-descriptions-item label-class-name="my-label">
		    <template slot="label">
		      <i class="el-icon-office-building"></i>
          活动里程抵扣:
		    </template>
        {{ form.levelMiles == null ? 0 : form.levelMiles }}
		  </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" v-if="form.params">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              跟车运营抵扣:
            </template>
            {{ form.params.discountPrice == null ? 0 : form.params.discountPrice}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              服务费单价:
            </template>
            0
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              服务费:
            </template>
            0
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              订单总额:
            </template>
            {{form.totalOrderAmount}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              实付金额:
            </template>
            {{ form.payAmount }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              支付类型:
            </template>
            <span> {{ form.payType }}</span>
          </el-descriptions-item>
           <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              支付状态:
            </template>
            <span><dict-tag :options="dict.type.pay_status" :value="form.payStatus"/></span>
          </el-descriptions-item> 
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-time"></i>
              支付时间:
            </template>
            {{ parseTime(form.payTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-dianchi iconfont"></i>
              订单折扣:
            </template>
            <span v-if="!form.orderPriceDiscount || form.orderPriceDiscount === 1">{{ '无折扣' }}</span>
            <span v-if="form.orderPriceDiscount === 0">{{ '折扣有误' }}</span>
            <span v-if="form.orderPriceDiscount && form.orderPriceDiscount !== 1 && form.orderPriceDiscount !== 0">{{ form.orderPriceDiscount*10 + '折' }}</span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="c1" style="height:30px"></div>
        <el-descriptions class="margin-top" title="卡券抵扣信息" :column="3" :size="size" border>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-34 iconfont"></i>
              卡券Id
            </template>
            {{ form.creditCardId }}
          </el-descriptions-item>
          <!-- <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-34 iconfont"></i>
              卡券类型
            </template>
            <span>{{this.formatOptions(form, this.vipTypeOptions, `vipType`, `dictValue`, `dictLabel`)}}</span>
          </el-descriptions-item> -->
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-zq-34 iconfont"></i>
              卡券抵扣费用
            </template>
            {{ form.amountCreditCard }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="c1" style="height:30px" v-if="form.reduceTime"></div>
        <el-descriptions v-if="form.reduceTime" class="margin-top" title="充电减免信息" :column="2" :size="size" border>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              减免人
            </template>
            {{ form.reduceBy }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              减免时间
            </template>
            {{ form.reduceTime }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              减免图片
            </template>
            <span v-for="(item,index) in reduceDetailList" :key="index" v-if="reduceDetailList.length !== 0">
                <el-image
                  :preview-src-list="reduceDetailList"
                  :src="item"
                  style="width: 100px; height: 100px;margin-right: 30px"
                />
              </span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="c1" style="height:30px" v-if="form.detailList && form.detailList.length > 0"></div>
        
      </div>
      <!-- 填充高度：80px -->
      <div class="fill_height"></div>
    </el-drawer>

  </div>
</template>

<script>
import { listOrder, getOrder,totalPrice} from "@/api/zq/electricOrder";
import { listArea } from "@/api/zq/area";
import { listStation } from "@/api/zq/station";

export default {
  name: "Order",
  dicts: ['pay_status', 'electric_order_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 是否显示汇总
			isShow: false,
      // 总条数
      total: 0,
      // 换电订单表格数据
      orderList: [],
      size: ' ',
      value: [],//站点搜索
      summaryData: [],
      open2: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
       // 换电状态1换电中2换电异常3换电成功4已完结字典
       orderStatusOptions: [],
       // 支付状态0初始1待支付2支付成功字典
       payStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userPhone: null,
        licensePlate: null,
        vin: null,
        stationId: null,
        electricStatus: null,
        endurance: null,
        subsidy: null,
        city: null,
        oldSoc: null,
        newSoc: null,
        oldBatteryCode: null,
        newBatteryCode: null,
        overTime: null,
        lastMileage: null,
        nowMileage: null,
        derateMileage: null,
        chargingMileage: null,
        totalOrderAmount: null,
        amountCreditCard: null,
        payStatus: null,
        payTime: null,
        creditCardId: null,
        payAmount: null
      },
      // 表单参数
      form: {},
      prop: {
          lazy: true,
          // checkStrictly: true,
          multiple: false,
          lazyLoad(node, resolve) {
            if (node.level == 0) {
              listArea().then(response => {
                this.openAreaOptions = response.data;
                const cities = response.data.map((value, i) => ({
                  value: value.areaId,
                  label: value.name,
                  leaf: node.level >= 2
                }));
                resolve(cities);
              })
            } 
            else if (node.level == 1) {
              listStation({stationCityId: node.value}).then(response => {
                const areas = response.data.map((value, i) => ({
                  value: value.stationId,
                  label: value.stationName,
                  leaf: node.level >= 1
                }));
                resolve(areas);
              });
            } else {
              node.loading = false;
              node.loaded = false;
            }
          }
        },

    };
  },
  created() {
    // this.getList();
  },
  methods: {
    getMileageRate(stationId) {  
      // 根据 stationId 的值返回不同的里程计费单价  
      if (stationId > 13 && stationId < 36) {  
        return 0.33;  
      } else {  
        return 0.3;  
      }  
    } , 
    /** 查询换电订单列表 */
    getList() {
      console.log(this.queryParams)
      if(this.queryParams.stationId==null){
        this.$modal.msgError("请选择站点！");
        return;
      }
      this.loading = true;
      listOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      totalPrice(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.summaryData= [],
        this.summaryData = this.summaryData.concat(response.data);
      });
    },
    
    handleClose() {
        this.open2 = false
        this.reduceDetailList = []
      },
 //选择站点触发时间
 selectElectric: function (event) {
        if (event.length == 1) {
          this.queryParams.cityId = event[0]
          this.queryParams.stationId = ''
        } else {
          this.queryParams.stationId = event[1]
          this.queryParams.cityId = ''
        }
      },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        userPhone: null,
        licensePlate: null,
        vin: null,
        stationId: null,
        electricStatus: null,
        endurance: null,
        subsidy: null,
        city: null,
        oldSoc: null,
        newSoc: null,
        oldBatteryCode: null,
        newBatteryCode: null,
        createTime: null,
        overTime: null,
        lastMileage: null,
        nowMileage: null,
        derateMileage: null,
        chargingMileage: null,
        totalOrderAmount: null,
        amountCreditCard: null,
        payStatus: null,
        payTime: null,
        creditCardId: null,
        payAmount: null
      };
      this.resetForm("form");
    },
    queryDetails(row) {
        this.reset();
        const orderId = row.orderId || this.ids;
        getOrder(orderId).then((response) => {
          this.form = response.data;
          // if (response.data.pic) {
          //   this.reduceDetailList = response.data.pic.split(',');
          // }
          this.open2 = true;
          this.title = "订单详情";
        });
      },
    /** 搜索按钮操作 */
    handleQuery() {
      
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.dateRange = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加换电订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改换电订单";
      });
    },
    summaryShow() {
        if (this.isShow) {
          this.isShow = false
        } else {
          this.isShow = true
        }
      },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    
    getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '汇总';
            return;
          }
          // 需要计算汇总的字段
          // const includingOptions = [`totalOrderAmount`,`amountCreditCard`,`payAmount`]
          const includingOptions = [`totalOrderAmount`]
          const values = data.map(item => Number(item[column.property]));
          if (includingOptions.includes(column.property)) {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index] = sums[index].toFixed(2);
              if ([`balance`].includes(column.property)) {
                sums[index] = sums[index]/100 + '元';
              } else{
				  sums[index] = sums[index] + '元';
			  }
            } else {
              sums[index] = '';
            }
          } else {
            return "";
          }
        });
        return sums;
      },

  }
};
</script>
